#include "widget.h"
#include "ui_widget.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QByteArray>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    webSocket=new QWebSocket;
    connect(webSocket, &QWebSocket::connected, this, &Widget::onConnected);
    connect(webSocket, QOverload<QAbstractSocket::SocketError>::of(&QWebSocket::error),
            this, &Widget::onError);
    connect(webSocket, &QWebSocket::disconnected, this, &Widget::onDisconnected);

    // connect(m_webSocket, &QWebSocket::textMessageReceived, this, &WebSocketClient::onTextMessageReceived);


    QUrl url(QStringLiteral("ws://192.168.10.142:1700/"));
    webSocket->open(url);
}

Widget::~Widget()
{
    delete ui;
    webSocket->close();
    webSocket->deleteLater();
}

void Widget::sendMessage(const QString &message)
{
    if (webSocket->state() == QAbstractSocket::ConnectedState) {
        // webSocket->sendTextMessage(QWebSocketProtocol::TextMessage, message);
        qDebug() << "Message sent:" << message;
    } else {
        qDebug() << "WebSocket is not connected.";
    }
}

void Widget::on_pushButton_clicked()
{
    QJsonObject rootObject;
    rootObject["major"] = 1;
    rootObject["minor"] = 35;
    // rootObject["value"] = 0;
    QJsonDocument jsonDoc(rootObject);
    QByteArray jsonByteArray = jsonDoc.toJson(QJsonDocument::Compact);
    // sendMessage(QString(jsonByteArray));
    webSocket->sendTextMessage(QString(jsonByteArray));
}

void Widget::onConnected()
{
    qDebug() << "WebSocket connected";
}

void Widget::onError(QAbstractSocket::SocketError error)
{
    qDebug() << "WebSocket error:" << error;
}

void Widget::onDisconnected()
{
    qDebug() << "WebSocket disconnected";
}

